<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { uploadFiles, downloadFile as apiDownloadFile } from '../api/fileService.js'
import { renderAsync } from 'docx-preview'

// 上传状态
const uploadStatus = ref({
  supervision_record: {
    file: null,
    progress: 0,
    status: 'waiting' // waiting, uploading, success, error
  },
  correction_order: {
    file: null,
    progress: 0,
    status: 'waiting'
  }
})

// 处理文件上传
async function handleFileUpload(itemId, files) {
  if (!files || files.length === 0) return
  
  const file = files[0]
  uploadStatus.value[itemId] = {
    file,
    progress: 0,
    status: 'uploading'
  }
  
  try {
    // 调用真实的上传API
    const result = await uploadFiles([file], (progress) => {
      // 更新上传进度
      uploadStatus.value[itemId].progress = progress
    })
    
    // 上传成功
    uploadStatus.value[itemId].status = 'success'
    
    // 更新文件路径 - 在实际应用中，这里应该使用后端返回的文件路径
    const stageItem = stages.value[0].items.find(i => i.id === itemId)
    if (stageItem) {
      // 为了演示，我们仍然使用本地URL，但在实际应用中应该使用后端返回的路径
      stageItem.filePath = URL.createObjectURL(file)
      // 如果后端返回了fileId，可以保存它用于后续操作
      if (result.fileId) {
        stageItem.fileId = result.fileId
      }
    }
    
    console.log('文件上传成功:', result)
    
    // 检查是否可以生成材料
    checkGenerateMaterialsStatus()
  } catch (error) {
    // 上传失败
    uploadStatus.value[itemId].status = 'error'
    console.error('文件上传失败:', error)
    // 检查是否可以生成材料
    checkGenerateMaterialsStatus()
    // 这里可以添加错误提示
  }
}

// 定义案件阶段数据
const stages = ref([
  { id: 1, name: '材料上传', expanded: true, items: [
    { id: 'materials_upload', name: '材料上传', type: 'docx', filePath: '' }
  ]},
  { id: 2, name: '立案审批', expanded: false, items: [
    { id: 'case_approval', name: '立案审批表', type: 'docx', filePath: '' }
  ]},
  { id: 3, name: '收集案件证据', expanded: false, items: [
    { id: 'interrogation_record', name: '询问笔录', type: 'docx', filePath: '' },
    { id: 'collective_proposal', name: '集体议案', type: 'docx', filePath: '' }
  ]},
  { id: 4, name: '处罚材料', expanded: false, items: [
    { id: 'admin_punishment_notice', name: '行政处罚告知笔录', type: 'docx', filePath: '' },
    { id: 'administrative_penalty_decision', name: '行政处罚决定书', type: 'docx', filePath: '', canGenerate: true }
  ]}
])

// 当前选择的阶段和项目
const selectedStage = ref('materials_upload')

// 当前预览的文档
const previewDocument = ref(null)

// docx-preview相关
const interrogationPreviewContainer = ref(null)
const penaltyPreviewContainer = ref(null)
const noticePreviewContainer = ref(null)
const generalPreviewContainer = ref(null)
const proposalPreviewContainer = ref(null)
const isLoadingDocx = ref(false)

// 集体议案相关状态
const proposalContent = ref('')
const isGeneratingProposal = ref(false)
const proposalError = ref('')
const proposalGenerated = ref(false)

// 检查文件是否存在
const fileExists = (filePath) => {
  if (!filePath) return false
  // 在实际应用中，可以通过API检查文件是否存在
  // 这里简单返回true，假设所有文件都存在
  return true
}

// 生成集体议案
async function generateCollectiveProposal() {
  if (!proposalContent.value.trim()) {
    proposalError.value = '请输入议案内容'
    return
  }
  
  isGeneratingProposal.value = true
  proposalError.value = ''
  
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 这里应该调用后端API生成集体议案
    // const response = await apiGenerateProposal(proposalContent.value)
    
    // 模拟生成成功
    proposalGenerated.value = true
    
    // 查找集体议案项目并更新状态
    const stage = stages.value.find(s => s.id === 3)
    if (stage) {
      const proposalItem = stage.items.find(i => i.id === 'collective_proposal')
      if (proposalItem) {
        // 在实际应用中，这里应该使用后端返回的文件路径
        proposalItem.filePath = 'mock_proposal_path.docx'
      }
    }
    
    console.log('集体议案生成成功')
  } catch (error) {
    proposalError.value = '生成集体议案失败，请重试'
    console.error('生成集体议案失败:', error)
  } finally {
    isGeneratingProposal.value = false
  }
}

// 下载集体议案
async function downloadCollectiveProposal() {
  try {
    const stage = stages.value.find(s => s.id === 3)
    if (stage) {
      const proposalItem = stage.items.find(i => i.id === 'collective_proposal')
      if (proposalItem && proposalItem.filePath) {
        // 在实际应用中，这里应该调用后端API下载文件
        // await apiDownloadFile(proposalItem.filePath)
        
        // 模拟下载提示
        console.log('下载集体议案:', proposalItem.filePath)
        alert('集体议案下载成功')
      }
    }
  } catch (error) {
    console.error('下载集体议案失败:', error)
    alert('下载集体议案失败，请重试')
  }
}

// 获取文件URL
const getFileUrl = (item) => {
  if (!item || !item.filePath) return ''
  return item.filePath
}

// 用于生成材料功能
const canGenerateMaterials = ref(false)
const isGenerating = ref(false)

// 检查是否已生成立案审批表
const hasGeneratedCaseApproval = computed(() => {
  const caseApprovalStage = stages.value.find(stage => stage.id === 2)
  if (!caseApprovalStage) return false

  const caseApprovalItem = caseApprovalStage.items.find(item => item.id === 'case_approval')
  return caseApprovalItem && caseApprovalItem.jsonData && caseApprovalItem.filePath
})

// 检查是否已生成询问笔录
const interrogationGenerated = computed(() => {
  const interrogationStage = stages.value.find(stage => stage.id === 3)
  if (!interrogationStage) return false

  const interrogationItem = interrogationStage.items.find(item => item.id === 'interrogation_record')
  return interrogationItem && interrogationItem.filePath
})

// 检查是否可以生成材料
function checkGenerateMaterialsStatus() {
  const supervisionRecord = uploadStatus.value.supervision_record
  const correctionOrder = uploadStatus.value.correction_order

  console.log('检查生成材料状态:', {
    supervisionRecord: supervisionRecord.status,
    correctionOrder: correctionOrder.status
  })

  // 只有当两个文件都上传成功后，才可以生成材料
  canGenerateMaterials.value =
    supervisionRecord.status === 'success' &&
    correctionOrder.status === 'success'

  console.log('可以生成材料:', canGenerateMaterials.value)
}

import { sendFilesToBackend, generateInterrogationRecordFromJson, generatePenaltyDecision, generateAdminPunishmentNotice, generateAdminPunishmentNoticeFromFile } from '../api/fileService.js'

// 生成材料 - DifyChangeController返回JSON响应，包含文件路径用于预览
async function generateMaterials() {
  if (!canGenerateMaterials.value) return

  console.log('开始生成材料流程...')
  console.log('当前上传状态:', uploadStatus.value)

  // 显示加载弹窗
  isGenerating.value = true

  try {
    console.log('开始发送文件到后端...')
    const result = await sendFilesToBackend()
    console.log('文件发送成功:', result)

    // 保存生成的文件信息到stages，用于后续预览
    const caseApprovalStage = stages.value.find(stage => stage.id === 2)
    if (caseApprovalStage) {
      const caseApprovalItem = caseApprovalStage.items.find(item => item.id === 'case_approval')
      if (caseApprovalItem) {
        // 保存文件路径用于预览和下载
        caseApprovalItem.filePath = result.filePath || ''
        caseApprovalItem.htmlPath = result.htmlPath || ''
        caseApprovalItem.fileName = result.fileName
        caseApprovalItem.jsonData = result.jsonData
        caseApprovalItem.generated = true
        console.log('已保存立案审批表信息到前端状态:', caseApprovalItem)
      }
    }

    // 重置上传状态
    uploadStatus.value = {
      supervision_record: {
        file: null,
        progress: 0,
        status: 'waiting'
      },
      correction_order: {
        file: null,
        progress: 0,
        status: 'waiting'
      }
    }

    // 更新生成材料状态
    canGenerateMaterials.value = false

    // 显示成功消息
    alert(`立案审批表已生成: ${result.fileName}\n\n文件已保存到服务器，您可以在左侧菜单点击"立案审批"查看预览。`)
    console.log('材料生成成功！立案审批表可以预览。')

  } catch (error) {
    console.error('生成材料时出错:', error)
    alert(`生成材料失败: ${error.message}`)
  } finally {
    // 隐藏加载弹窗
    isGenerating.value = false
  }
}

// 生成笔录 - 自动使用已生成的立案审批表JSON数据
async function generateInterrogation() {
  console.log('开始生成笔录流程...')

  // 获取已保存的立案审批表JSON数据
  const caseApprovalStage = stages.value.find(stage => stage.id === 2)
  if (!caseApprovalStage) {
    alert('未找到立案审批表阶段')
    return
  }

  const caseApprovalItem = caseApprovalStage.items.find(item => item.id === 'case_approval')
  if (!caseApprovalItem || !caseApprovalItem.jsonData) {
    alert('未找到立案审批表数据，请先生成立案审批表')
    return
  }

  console.log('使用立案审批表JSON数据:', caseApprovalItem.jsonData)

  // 显示加载弹窗
  isGenerating.value = true

  try {
    console.log('开始调用笔录生成API...')
    const result = await generateInterrogationRecordFromJson(caseApprovalItem.jsonData)
    console.log('笔录生成成功:', result)

    // 保存笔录信息到前端状态
    const interrogationStage = stages.value.find(stage => stage.id === 3)
    if (interrogationStage) {
      const interrogationItem = interrogationStage.items.find(item => item.id === 'interrogation_record')
      if (interrogationItem) {
        interrogationItem.filePath = result.filePath || ''
        interrogationItem.htmlPath = result.htmlPath || ''
        interrogationItem.fileName = result.fileName
        interrogationItem.htmlContent = result.htmlContent
        interrogationItem.generated = true
        console.log('已保存询问笔录信息到前端状态:', interrogationItem)

        // 自动切换到询问笔录预览页面
        await nextTick()  // 等待状态更新
        selectStageItem(interrogationItem)
        console.log('已自动切换到询问笔录预览页面')

        // 显示成功消息（在切换页面后延迟显示，避免阻塞）
        setTimeout(() => {
          alert(`询问笔录已生成: ${result.fileName}`)
        }, 500)
      }
    }

    console.log('笔录生成成功！询问笔录可以预览。')

  } catch (error) {
    console.error('生成笔录时出错:', error)
    alert(`生成笔录失败: ${error.message}`)
  } finally {
    // 隐藏加载弹窗
    isGenerating.value = false
  }
}

// 获取笔录的HTML内容
function getInterrogationHtmlContent() {
  const interrogationStage = stages.value.find(stage => stage.id === 3)
  if (!interrogationStage) return null

  const interrogationItem = interrogationStage.items.find(item => item.id === 'interrogation_record')
  return interrogationItem ? interrogationItem.htmlContent : null
}

// 下载当前询问笔录
function downloadCurrentInterrogation() {
  const interrogationStage = stages.value.find(stage => stage.id === 3)
  if (!interrogationStage) return

  const interrogationItem = interrogationStage.items.find(item => item.id === 'interrogation_record')
  if (interrogationItem && interrogationItem.filePath) {
    downloadFile(interrogationItem.filePath)
  }
}

// ==================== 行政处罚决定书相关功能 ====================

// 处罚决定书文件上传状态
const penaltyFiles = ref({
  caseApproval: null,     // 立案审批表文件
  interrogation: null,    // 询问笔录文件
  evidence: []            // 证据文件数组
})

// 检查是否已生成处罚决定书
const penaltyDecisionGenerated = computed(() => {
  const penaltyStage = stages.value.find(stage => stage.id === 4)
  if (!penaltyStage) return false

  const penaltyItem = penaltyStage.items.find(item => item.id === 'administrative_penalty_decision')
  return penaltyItem && penaltyItem.filePath
})

// 检查是否可以生成处罚决定书（必须上传立案审批表）
const canGeneratePenalty = computed(() => {
  return penaltyFiles.value.caseApproval !== null
})

// 处理文件选择
function handlePenaltyFileSelect(fileType, event) {
  const files = event.target.files
  if (!files || files.length === 0) return

  if (fileType === 'caseApproval') {
    penaltyFiles.value.caseApproval = files[0]
    console.log('已选择立案审批表:', files[0].name)
  } else if (fileType === 'interrogation') {
    penaltyFiles.value.interrogation = files[0]
    console.log('已选择询问笔录:', files[0].name)
  } else if (fileType === 'evidence') {
    // 证据文件可以多选
    penaltyFiles.value.evidence = [...penaltyFiles.value.evidence, ...Array.from(files)]
    console.log('已选择证据文件:', penaltyFiles.value.evidence.length, '个')
  }
}

// 移除证据文件
function removePenaltyEvidenceFile(index) {
  penaltyFiles.value.evidence.splice(index, 1)
  console.log('移除证据文件，剩余:', penaltyFiles.value.evidence.length, '个')
}

// 生成行政处罚决定书
async function generatePenaltyDecisionDoc() {
  if (!canGeneratePenalty.value) return

  console.log('开始生成行政处罚决定书...')
  console.log('立案审批表:', penaltyFiles.value.caseApproval?.name)
  console.log('询问笔录:', penaltyFiles.value.interrogation?.name)
  console.log('证据文件:', penaltyFiles.value.evidence.length, '个')

  // 显示加载弹窗
  isGenerating.value = true

  try {
    const result = await generatePenaltyDecision(
      penaltyFiles.value.caseApproval,
      penaltyFiles.value.interrogation,
      penaltyFiles.value.evidence
    )
    console.log('处罚决定书生成成功:', result)

    // 保存生成的文件信息到stages
    const penaltyStage = stages.value.find(stage => stage.id === 4)
    if (penaltyStage) {
      const penaltyItem = penaltyStage.items.find(item => item.id === 'administrative_penalty_decision')
      if (penaltyItem) {
        penaltyItem.filePath = result.filePath || ''
        penaltyItem.htmlPath = result.htmlPath || ''
        penaltyItem.fileName = result.fileName
        penaltyItem.htmlContent = result.htmlContent
        penaltyItem.jsonData = result.jsonData
        penaltyItem.generated = true
        penaltyItem.evidenceFiles = result.evidenceFiles
        penaltyItem.lawBasis = result.lawBasis
        penaltyItem.punishmentAmount = result.punishmentAmount
        console.log('已保存处罚决定书信息到前端状态:', penaltyItem)
      }
    }

    // 重置文件上传状态
    penaltyFiles.value = {
      caseApproval: null,
      interrogation: null,
      evidence: []
    }

    // 显示成功消息
    alert(`行政处罚决定书已生成: ${result.fileName}\n\n文件已保存到服务器，您可以在左侧菜单点击"行政处罚决定书"查看预览。`)
    console.log('处罚决定书生成成功！可以预览。')

  } catch (error) {
    console.error('生成处罚决定书时出错:', error)
    alert(`生成处罚决定书失败: ${error.message}`)
  } finally {
    // 隐藏加载弹窗
    isGenerating.value = false
  }
}

// 获取处罚决定书的HTML内容
function getPenaltyDecisionHtmlContent() {
  const penaltyStage = stages.value.find(stage => stage.id === 4)
  if (!penaltyStage) return null

  const penaltyItem = penaltyStage.items.find(item => item.id === 'administrative_penalty_decision')
  return penaltyItem ? penaltyItem.htmlContent : null
}

// 下载处罚决定书
function downloadPenaltyDecision() {
  const penaltyStage = stages.value.find(stage => stage.id === 4)
  if (!penaltyStage) return

  const penaltyItem = penaltyStage.items.find(item => item.id === 'administrative_penalty_decision')
  if (penaltyItem && penaltyItem.filePath) {
    downloadFile(penaltyItem.filePath)
  }
}

// ==================== 行政处罚决定书相关功能结束 ====================

// ==================== 行政处罚告知笔录相关功能 ====================

// 告知笔录文件上传状态
const noticeFiles = ref({
  caseApproval: null,     // 立案审批表文件
  interrogation: null     // 询问笔录文件
})

// 告知笔录选择的告知类型
const selectedGaozhiType = ref('') // '处罚前告知' 或 '听证告知'

// 检查是否已生成告知笔录
const adminPunishmentNoticeGenerated = computed(() => {
  const stage = stages.value.find(s => s.id === 4)
  if (!stage) return false

  const item = stage.items.find(i => i.id === 'admin_punishment_notice')
  return item && item.filePath
})

// 检查是否可以生成告知笔录（必须上传立案审批表、询问笔录，并选择告知类型）
const canGenerateNotice = computed(() => {
  return noticeFiles.value.caseApproval !== null &&
         noticeFiles.value.interrogation !== null &&
         selectedGaozhiType.value !== ''
})

// 处理告知笔录文件选择
function handleNoticeFileSelect(fileType, event) {
  const files = event.target.files
  if (!files || files.length === 0) return

  if (fileType === 'caseApproval') {
    noticeFiles.value.caseApproval = files[0]
    console.log('已选择立案审批表:', files[0].name)
  } else if (fileType === 'interrogation') {
    noticeFiles.value.interrogation = files[0]
    console.log('已选择询问笔录:', files[0].name)
  }
}

// 生成行政处罚告知笔录
async function generateAdminPunishmentNoticeDoc() {
  if (!canGenerateNotice.value) {
    alert('请上传立案审批表和询问笔录文件，并选择告知类型')
    return
  }

  console.log('开始生成行政处罚告知笔录...')
  console.log('立案审批表:', noticeFiles.value.caseApproval?.name)
  console.log('询问笔录:', noticeFiles.value.interrogation?.name)
  console.log('告知类型:', selectedGaozhiType.value)

  // 显示加载弹窗
  isGenerating.value = true

  try {
    console.log('开始调用告知笔录生成API...')
    const result = await generateAdminPunishmentNoticeFromFile(
      noticeFiles.value.caseApproval,
      noticeFiles.value.interrogation,
      selectedGaozhiType.value
    )
    console.log('告知笔录生成成功:', result)

    // 保存告知笔录信息到前端状态
    const stage = stages.value.find(s => s.id === 4)
    if (stage) {
      const noticeItem = stage.items.find(i => i.id === 'admin_punishment_notice')
      if (noticeItem) {
        noticeItem.filePath = result.filePath || ''
        noticeItem.htmlPath = result.htmlPath || ''
        noticeItem.fileName = result.fileName
        noticeItem.jsonData = result.jsonData
        noticeItem.chaiLiangAdvice = result.chaiLiangAdvice
        noticeItem.lawBasis = result.lawBasis
        noticeItem.punishmentAmount = result.punishmentAmount
        noticeItem.generated = true
        console.log('已保存告知笔录信息到前端状态:', noticeItem)
      }
    }

    // 重置文件上传状态
    noticeFiles.value = {
      caseApproval: null,
      interrogation: null
    }
    selectedGaozhiType.value = ''

    // 显示成功消息
    alert(`行政处罚告知笔录已生成: ${result.fileName}\n\n文件已保存到服务器，您可以在左侧菜单点击"行政处罚告知笔录"查看预览。`)
    console.log('告知笔录生成成功！可以预览。')

  } catch (error) {
    console.error('生成告知笔录时出错:', error)
    alert(`生成告知笔录失败: ${error.message}`)
  } finally {
    // 隐藏加载弹窗
    isGenerating.value = false
  }
}

// 下载告知笔录
function downloadAdminPunishmentNotice() {
  const stage = stages.value.find(s => s.id === 4)
  if (!stage) return

  const noticeItem = stage.items.find(i => i.id === 'admin_punishment_notice')
  if (noticeItem && noticeItem.filePath) {
    downloadFile(noticeItem.filePath)
  }
}

// ==================== 行政处罚告知笔录相关功能结束 ====================

// 对话框消息
const chatMessages = ref([
  { sender: 'system', content: '欢迎回来，管理员' }
])
const chatInput = ref('')
const isChatExpanded = ref(false)
const chatHeight = ref(150)
const isDragging = ref(false)
const startY = ref(0)
const startHeight = ref(0)

// 切换阶段展开/收起
function toggleStage(stageId) {
  const stage = stages.value.find(s => s.id === stageId)
  if (stage) {
    stage.expanded = !stage.expanded
  }
}

// 使用docx-preview加载Word文档
async function loadDocumentWithDocxPreview(filePath) {
  if (!filePath) return

  isLoadingDocx.value = true

  try {
    console.log('开始加载Word文档:', filePath)

    // 获取文档的blob
    const response = await fetch(filePath)
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }

    const blob = await response.blob()
    console.log('文档blob获取成功')

    // 等待DOM更新
    await nextTick()

    // 根据当前显示的页面获取对应的容器
    let container = null
    if (selectedStage.value === 'interrogation_record') {
      container = interrogationPreviewContainer.value
    } else if (selectedStage.value === 'administrative_penalty_decision') {
      container = penaltyPreviewContainer.value
    } else if (selectedStage.value === 'admin_punishment_notice') {
      container = noticePreviewContainer.value
    } else {
      container = generalPreviewContainer.value
    }

    if (!container) {
      throw new Error('预览容器未找到')
    }

    // 清空容器
    container.innerHTML = ''

    // 使用docx-preview渲染
    await renderAsync(blob, container, undefined, {
      className: 'docx-preview-content',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      ignoreLastRenderedPageBreak: true,
      experimental: false,
      trimXmlDeclaration: true,
      useBase64URL: false,
      useMathMLPolyfill: false,
      renderChanges: false,
      renderHeaders: true,
      renderFooters: true,
      renderFootnotes: true,
      renderEndnotes: true
    })

    console.log('Word文档渲染成功')

  } catch (error) {
    console.error('加载Word文档失败:', error)

    // 根据当前页面获取容器并显示错误
    let container = null
    if (selectedStage.value === 'interrogation_record') {
      container = interrogationPreviewContainer.value
    } else if (selectedStage.value === 'administrative_penalty_decision') {
      container = penaltyPreviewContainer.value
    } else if (selectedStage.value === 'admin_punishment_notice') {
      container = noticePreviewContainer.value
    } else {
      container = generalPreviewContainer.value
    }

    if (container) {
      container.innerHTML = `
        <div style="text-align: center; padding: 40px; color: #999;">
          <h3>文档加载失败</h3>
          <p>无法加载文档预览</p>
          <p>错误：${error.message}</p>
        </div>
      `
    }
  } finally {
    isLoadingDocx.value = false
  }
}

// 选择阶段项目
function selectStageItem(item) {
  console.log('选择阶段项目:', item)
  selectedStage.value = item.id
  previewDocument.value = item

  // 如果是Word文档，使用docx-preview预览
  if (item.type === 'docx' && item.filePath) {
    loadDocumentWithDocxPreview(item.filePath)
  }

  console.log('设置预览文档:', {
    name: item.name,
    type: item.type,
    filePath: item.filePath
  })
}

// 选择案件
function selectCase(caseItem) {
  selectedCase.value = caseItem
}

// 发送消息
function sendMessage() {
  if (chatInput.value.trim()) {
    chatMessages.value.push({ sender: 'user', content: chatInput.value })
    chatInput.value = ''
    // 模拟系统回复
    setTimeout(() => {
      chatMessages.value.push({ sender: 'system', content: '收到您的消息，正在处理...' })
    }, 1000)
  }
}

// 下载文件
async function downloadFile(filePath) {
  if (!filePath) return

  console.log('开始下载文件:', filePath)

  // 如果是生成的文档（包含/api/files/download/generated/），直接使用URL下载
  if (filePath.includes('/api/files/download/generated/')) {
    try {
      // 直接使用提供的下载URL
      const link = document.createElement('a')
      link.href = filePath
      link.download = '' // 让浏览器从响应头中获取文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      console.log('文档下载成功:', filePath)
      return
    } catch (error) {
      console.error('下载失败:', error)
      return
    }
  }

  // 如果文档有fileId，使用API下载；否则使用本地下载
  if (previewDocument.value && previewDocument.value.fileId) {
    try {
      // 从路径中提取文件名
      const fileName = filePath.split('/').pop() || '文档.docx'
      await apiDownloadFile(previewDocument.value.fileId, fileName)
    } catch (error) {
      console.error('API下载失败，尝试本地下载:', error)
      // 降级到本地下载
      fallbackLocalDownload(filePath)
    }
  } else {
    // 本地下载
    fallbackLocalDownload(filePath)
  }
}

// 本地下载作为降级方案
function fallbackLocalDownload(filePath) {
  // 创建一个临时的a标签用于下载
  const link = document.createElement('a')
  link.href = filePath
  // 从路径中提取文件名
  const fileName = filePath.split('/').pop()
  link.download = fileName || '立案审批表.docx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 在新窗口中打开文件
function openInNewTab(filePath) {
  if (filePath) {
    window.open(filePath, '_blank')
  }
}

// 处理iframe加载错误
function handleIframeError(event) {
  console.log('iframe加载失败:', event)
  // 这里可以添加备选方案的逻辑
}

// 预览PDF文件
function previewPdf(item) {
  if (!item || !item.filePath) {
    console.error('文件路径不存在')
    return
  }
  
  // 不再跳转到新窗口，而是在当前页面预览PDF
  previewDocument.value = {
    name: item.name,
    type: 'pdf',
    filePath: item.filePath
  }
}

// 全屏查看PDF
function viewFullScreenPdf(item) {
  if (!item || !item.filePath) {
    console.error('文件路径不存在')
    return
  }
  
  console.log('正在打开全屏PDF预览:', item.filePath)
  
  // 创建全屏预览层
  const overlay = document.createElement('div')
  overlay.className = 'pdf-fullscreen-overlay'
  
  // 创建PDF查看器 - 使用iframe而不是object，以确保更好的兼容性
  const viewer = document.createElement('iframe')
  viewer.src = item.filePath
  viewer.className = 'pdf-fullscreen-viewer'
  viewer.setAttribute('allowfullscreen', 'true')
  
  // 创建关闭按钮
  const closeBtn = document.createElement('button')
  closeBtn.className = 'pdf-fullscreen-close'
  closeBtn.innerHTML = '×'
  closeBtn.onclick = (e) => {
    e.stopPropagation() // 阻止事件冒泡
    document.body.removeChild(overlay)
    document.body.style.overflow = 'auto'
  }
  
  // 组装并添加到页面
  overlay.appendChild(viewer)
  overlay.appendChild(closeBtn)
  document.body.appendChild(overlay)
  document.body.style.overflow = 'hidden'
  
  // 确保iframe加载完成
  viewer.onload = () => {
    console.log('PDF预览已加载')
  }
  
  // 防止点击overlay时关闭
  overlay.onclick = (e) => {
    e.stopPropagation()
  }
}

// 切换聊天框展开/折叠
function toggleChat() {
  isChatExpanded.value = !isChatExpanded.value
}

// 开始拖动
function startDrag(e) {
  if (!isChatExpanded.value) return
  
  isDragging.value = true
  startY.value = e.clientY
  startHeight.value = chatHeight.value
  
  // 添加全局事件监听
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}

// 拖动中
function onDrag(e) {
  if (!isDragging.value) return
  
  const deltaY = startY.value - e.clientY
  const newHeight = Math.max(50, Math.min(500, startHeight.value + deltaY))
  chatHeight.value = newHeight
}

// 停止拖动
function stopDrag() {
  isDragging.value = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 生命周期钩子
onMounted(() => {
  // 初始化时聊天框是折叠的
  isChatExpanded.value = false
  
  // 添加全局事件监听器，用于处理全屏PDF查看
  document.addEventListener('keydown', (e) => {
    // 按ESC键关闭全屏PDF
    if (e.key === 'Escape') {
      const overlay = document.querySelector('.pdf-fullscreen-overlay')
      if (overlay) {
        document.body.removeChild(overlay)
        document.body.style.overflow = 'auto'
      }
    }
  })
})
</script>

<template>
  <div class="container">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="header-left">
        <span class="header-title">AI智能研判</span>
        <span class="header-title">案件总览</span>
        <span class="header-title active">程序审查</span>
        <span class="header-title">证据审查</span>
        <span class="header-title">案件分析</span>
      </div>
      <div class="header-right">
        <button class="header-btn">关闭通道</button>
        <button class="header-btn">导出</button>
        <button class="header-btn">管理入口</button>
        <span class="header-user">欢迎回来，管理员</span>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="main-content">
      <!-- 左侧阶段菜单 -->
      <div class="left-panel">
        <div class="stage-menu">
          <div v-for="stage in stages" :key="stage.id" class="stage-item">
            <div class="stage-header" @click="toggleStage(stage.id)">
              <span class="stage-arrow">{{ stage.expanded ? '▼' : '▶' }}</span>
              <span class="stage-name">{{ stage.name }}</span>
            </div>
            <div v-if="stage.expanded" class="stage-submenu">
              <div v-for="item in stage.items" :key="item.id" 
                class="stage-subitem" 
                :class="{ active: selectedStage === item.id }"
                @click="selectStageItem(item)">
                {{ item.name }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧文档区域 -->
      <div class="right-panel">
        
        <!-- 材料上传与生成页面 -->
        <div v-if="selectedStage === 'materials_upload'" class="document-preview">
          <div class="preview-container">
              <div class="preview-header">
                <h3>上传监督检查记录与责令整改通知书</h3>
              </div>
              
              <div class="documents-upload-container">
              <!-- 监督检查记录上传 -->
              <div class="document-upload-item">
                <div class="document-upload-header">
                  <h4>监督检查记录</h4>
                  <span v-if="uploadStatus.supervision_record.status === 'success'" class="upload-status-badge success">✓ 已上传</span>
                  <span v-else-if="uploadStatus.supervision_record.status === 'uploading'" class="upload-status-badge uploading">⟳ 上传中</span>
                  <span v-else-if="uploadStatus.supervision_record.status === 'error'" class="upload-status-badge error">✗ 上传失败</span>
                  <span v-else class="upload-status-badge">○ 待上传</span>
                </div>
                <div class="upload-area" 
                     @dragover.prevent 
                     @drop.prevent="handleFileUpload('supervision_record', $event.dataTransfer.files)">
                  <div class="upload-content">
                    <div class="upload-icon">📤</div>
                    <p>拖放文件到此处上传</p>
                    <p>或</p>
                    <label class="upload-btn">
                      <input type="file" accept=".docx,.doc" @change="handleFileUpload('supervision_record', $event.target.files)" style="display: none;">
                      选择文件
                    </label>
                  </div>
                  <div v-if="uploadStatus.supervision_record.status === 'uploading'" class="upload-progress">
                    <div class="progress-bar" :style="{ width: uploadStatus.supervision_record.progress + '%' }"></div>
                    <span>{{ uploadStatus.supervision_record.progress }}%</span>
                  </div>
                  <div v-else-if="uploadStatus.supervision_record.status === 'success'" class="upload-success">
                    ✓ 上传成功
                    <button 
                      v-if="uploadStatus.supervision_record.file" 
                      @click="downloadFile(URL.createObjectURL(uploadStatus.supervision_record.file))" 
                      class="download-btn small">下载</button>
                  </div>
                  <div v-else-if="uploadStatus.supervision_record.status === 'error'" class="upload-error">
                    ✗ 上传失败，请重试
                  </div>
                </div>
              </div>
              
              <!-- 责令整改通知书上传 -->
              <div class="document-upload-item">
                <div class="document-upload-header">
                  <h4>责令整改通知书</h4>
                  <span v-if="uploadStatus.correction_order.status === 'success'" class="upload-status-badge success">✓ 已上传</span>
                  <span v-else-if="uploadStatus.correction_order.status === 'uploading'" class="upload-status-badge uploading">⟳ 上传中</span>
                  <span v-else-if="uploadStatus.correction_order.status === 'error'" class="upload-status-badge error">✗ 上传失败</span>
                  <span v-else class="upload-status-badge">○ 待上传</span>
                </div>
                <div class="upload-area" 
                     @dragover.prevent 
                     @drop.prevent="handleFileUpload('correction_order', $event.dataTransfer.files)">
                  <div class="upload-content">
                    <div class="upload-icon">📤</div>
                    <p>拖放文件到此处上传</p>
                    <p>或</p>
                    <label class="upload-btn">
                      <input type="file" accept=".docx,.doc" @change="handleFileUpload('correction_order', $event.target.files)" style="display: none;">
                      选择文件
                    </label>
                  </div>
                  <div v-if="uploadStatus.correction_order.status === 'uploading'" class="upload-progress">
                    <div class="progress-bar" :style="{ width: uploadStatus.correction_order.progress + '%' }"></div>
                    <span>{{ uploadStatus.correction_order.progress }}%</span>
                  </div>
                  <div v-else-if="uploadStatus.correction_order.status === 'success'" class="upload-success">
                    ✓ 上传成功
                    <button 
                      v-if="uploadStatus.correction_order.file" 
                      @click="downloadFile(URL.createObjectURL(uploadStatus.correction_order.file))" 
                      class="download-btn small">下载</button>
                  </div>
                  <div v-else-if="uploadStatus.correction_order.status === 'error'" class="upload-error">
                    ✗ 上传失败，请重试
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 生成材料按钮 -->
            <div class="generate-btn-container">
              <button
                class="generate-btn"
                :class="{ disabled: !canGenerateMaterials }"
                :disabled="!canGenerateMaterials"
                @click="generateMaterials"
              >
                生成立案审批表
              </button>
            </div>

            <!-- 提示信息 -->
            <div class="upload-tips">
              <p>💡 提示：请先上传监督检查记录和责令整改通知书，两个文件都上传成功后才能点击"生成材料"按钮。</p>
            </div>
          </div>
        </div>

        <!-- 询问笔录页面 - 仿照立案审批表样式 -->
        <div v-else-if="selectedStage === 'interrogation_record'" class="document-preview">
          <div class="preview-container">
            <div class="preview-header">
              <h3>询问笔录</h3>
              <div class="preview-actions">
                <span class="document-type">DOCX</span>
                <button v-if="interrogationGenerated"
                        class="download-word-btn"
                        @click="downloadCurrentInterrogation">
                  📥 下载Word文档
                </button>
              </div>
            </div>

            <div class="preview-content">
              <!-- 如果笔录已生成，显示预览 -->
              <div v-if="interrogationGenerated" class="docx-preview">
                <!-- 使用docx-preview组件预览 -->
                <div class="docx-frame-container">
                  <div ref="interrogationPreviewContainer" class="docx-preview-wrapper" v-show="!isLoadingDocx"></div>
                  <!-- 加载中 -->
                  <div v-if="isLoadingDocx" class="html-loading">
                    <div class="loading-spinner"></div>
                    <p>正在加载文档预览...</p>
                  </div>
                </div>
              </div>

              <!-- 如果笔录未生成，显示生成界面 -->
              <div v-else class="interrogation-generation-wrapper">
                <div class="interrogation-generation-container">
                  <div class="generation-info">
                    <div class="info-header">
                      <h4>📋 询问笔录生成说明</h4>
                    </div>
                    <div class="info-content">
                      <p>询问笔录将基于已生成的立案审批表内容自动生成，包含以下信息：</p>
                      <ul>
                        <li>案件基本信息和当事人详情</li>
                        <li>询问时间、地点和参与人员</li>
                        <li>标准化的询问程序和告知事项</li>
                        <li>案件事实的详细询问记录</li>
                        <li>当事人陈述和答辩内容</li>
                        <li>询问人员和被询问人签字确认</li>
                      </ul>
                    </div>
                  </div>

                  <div class="generation-status">
                    <div v-if="!hasGeneratedCaseApproval" class="status-waiting">
                      <div class="status-icon">⏳</div>
                      <h4>等待立案审批表生成</h4>
                      <p>请先完成立案审批表的生成，然后才能生成询问笔录。</p>
                      <p class="status-tip">💡 提示：请前往"材料上传"页面上传监督检查记录和责令整改通知书，然后生成立案审批表。</p>
                    </div>

                    <div v-else class="status-ready">
                      <div class="status-icon">✅</div>
                      <h4>准备就绪</h4>
                      <p>立案审批表已生成，现在可以生成询问笔录。</p>
                      <button
                        class="generate-interrogation-btn"
                        @click="generateInterrogation"
                        :disabled="isGenerating">
                        <span v-if="isGenerating">🔄 正在生成...</span>
                        <span v-else>📝 生成询问笔录</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 行政处罚告知笔录页面 -->
        <div v-else-if="selectedStage === 'admin_punishment_notice'" class="document-preview">
          <div class="preview-container">
            <div class="preview-header">
              <h3>行政处罚告知笔录</h3>
              <div class="preview-actions">
                <span class="document-type">DOCX</span>
                <button v-if="adminPunishmentNoticeGenerated"
                        class="download-word-btn"
                        @click="downloadAdminPunishmentNotice">
                  📥 下载Word文档
                </button>
              </div>
            </div>

            <div class="preview-content">
              <!-- 如果已生成，显示预览 -->
              <div v-if="adminPunishmentNoticeGenerated" class="docx-preview">
                <!-- 使用docx-preview组件预览 -->
                <div class="docx-frame-container">
                  <div ref="noticePreviewContainer" class="docx-preview-wrapper" v-show="!isLoadingDocx"></div>
                  <!-- 加载中 -->
                  <div v-if="isLoadingDocx" class="html-loading">
                    <div class="loading-spinner"></div>
                    <p>正在加载文档预览...</p>
                  </div>
                </div>
              </div>

              <!-- 如果未生成，显示生成界面 -->
              <div v-else class="notice-generation-wrapper">
                <div class="notice-generation-container">
                  <div class="generation-info">
                    <div class="info-header">
                      <h4>📋 行政处罚告知笔录生成说明</h4>
                    </div>
                    <div class="info-content">
                      <p>行政处罚告知笔录将基于已生成的立案审批表内容自动生成，包含以下信息：</p>
                      <ul>
                        <li>消防救援机构名称和执行单位</li>
                        <li>告知人和被告知人信息</li>
                        <li>案情简要描述</li>
                        <li>证据材料清单</li>
                        <li>法律依据条款</li>
                        <li>处罚对象和金额</li>
                        <li>权利告知事项</li>
                      </ul>
                    </div>
                  </div>

                  <div class="file-upload-section">
                    <h4>📁 上传案件文件</h4>

                    <!-- 立案审批表上传 -->
                    <div class="file-upload-item">
                      <div class="file-upload-header">
                        <label>立案审批表（必选）</label>
                        <span v-if="noticeFiles.caseApproval" class="file-status success">✓ 已选择</span>
                        <span v-else class="file-status">○ 未选择</span>
                      </div>
                      <div class="file-upload-control">
                        <input
                          type="file"
                          ref="noticeCaseApprovalInput"
                          accept=".docx,.doc"
                          @change="handleNoticeFileSelect('caseApproval', $event)"
                          style="display: none;">
                        <button class="select-file-btn" @click="$refs.noticeCaseApprovalInput.click()">
                          选择文件
                        </button>
                        <span v-if="noticeFiles.caseApproval" class="file-name">
                          {{ noticeFiles.caseApproval.name }}
                        </span>
                      </div>
                    </div>

                    <!-- 询问笔录上传 -->
                    <div class="file-upload-item">
                      <div class="file-upload-header">
                        <label>询问笔录（必选）</label>
                        <span v-if="noticeFiles.interrogation" class="file-status success">✓ 已选择</span>
                        <span v-else class="file-status">○ 未选择</span>
                      </div>
                      <div class="file-upload-control">
                        <input
                          type="file"
                          ref="noticeInterrogationInput"
                          accept=".docx,.doc"
                          @change="handleNoticeFileSelect('interrogation', $event)"
                          style="display: none;">
                        <button class="select-file-btn" @click="$refs.noticeInterrogationInput.click()">
                          选择文件
                        </button>
                        <span v-if="noticeFiles.interrogation" class="file-name">
                          {{ noticeFiles.interrogation.name }}
                        </span>
                      </div>
                    </div>

                    <!-- 告知类型选择 -->
                    <div class="gaozhi-type-selection">
                      <h5>请选择告知类型：</h5>
                      <div class="radio-group">
                        <label class="radio-label">
                          <input
                            type="radio"
                            v-model="selectedGaozhiType"
                            value="处罚前告知"
                            class="radio-input">
                          <span class="radio-text">处罚前告知</span>
                        </label>
                        <label class="radio-label">
                          <input
                            type="radio"
                            v-model="selectedGaozhiType"
                            value="听证告知"
                            class="radio-input">
                          <span class="radio-text">听证告知</span>
                        </label>
                      </div>
                    </div>

                    <!-- 生成按钮 -->
                    <div class="generate-btn-container">
                      <button
                        class="generate-notice-btn"
                        :class="{ disabled: !canGenerateNotice }"
                        :disabled="!canGenerateNotice || isGenerating"
                        @click="generateAdminPunishmentNoticeDoc">
                        <span v-if="isGenerating">🔄 正在生成...</span>
                        <span v-else>📝 生成行政处罚告知笔录</span>
                      </button>
                    </div>

                    <!-- 提示信息 -->
                    <div class="upload-tips">
                      <p>💡 提示：必须上传立案审批表文件、询问笔录文件，并选择告知类型才能生成行政处罚告知笔录。系统将自动调用裁量标准智能体获取法律依据和罚款金额建议。</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 行政处罚决定书上传页面 -->
        <div v-else-if="selectedStage === 'administrative_penalty_decision'" class="document-preview">
          <div class="preview-container">
            <div class="preview-header">
              <h3>行政处罚决定书</h3>
              <div class="preview-actions">
                <span class="document-type">DOCX</span>
                <button v-if="penaltyDecisionGenerated"
                        class="download-word-btn"
                        @click="downloadPenaltyDecision">
                  📥 下载Word文档
                </button>
              </div>
            </div>

            <div class="preview-content">
              <!-- 如果已生成，显示预览 -->
              <div v-if="penaltyDecisionGenerated" class="docx-preview">
                <!-- 使用docx-preview组件预览 -->
                <div class="docx-frame-container">
                  <div ref="penaltyPreviewContainer" class="docx-preview-wrapper" v-show="!isLoadingDocx"></div>
                  <!-- 加载中 -->
                  <div v-if="isLoadingDocx" class="html-loading">
                    <div class="loading-spinner"></div>
                    <p>正在加载文档预览...</p>
                  </div>
                </div>
              </div>

              <!-- 如果未生成，显示上传界面 -->
              <div v-else class="penalty-generation-wrapper">
                <div class="penalty-generation-container">
                  <div class="generation-info">
                    <div class="info-header">
                      <h4>📋 行政处罚决定书生成说明</h4>
                    </div>
                    <div class="info-content">
                      <p>行政处罚决定书将基于已生成的立案审批表和询问笔录内容自动生成，包含以下信息：</p>
                      <ul>
                        <li>违法行为人完整信息</li>
                        <li>案件事实认定（基于简要案情）</li>
                        <li>法律依据（来自裁量标准智能体）</li>
                        <li>处罚决定和罚款金额（来自裁量标准智能体）</li>
                        <li>证据材料清单（基于上传的证据文件）</li>
                        <li>权利告知和救济途径</li>
                      </ul>
                    </div>
                  </div>

                  <div class="file-upload-section">
                    <h4>📁 上传案件文件</h4>

                    <!-- 立案审批表上传 -->
                    <div class="file-upload-item">
                      <div class="file-upload-header">
                        <label>立案审批表（必选）</label>
                        <span v-if="penaltyFiles.caseApproval" class="file-status success">✓ 已选择</span>
                        <span v-else class="file-status">○ 未选择</span>
                      </div>
                      <div class="file-upload-control">
                        <input
                          type="file"
                          ref="caseApprovalInput"
                          accept=".docx,.doc"
                          @change="handlePenaltyFileSelect('caseApproval', $event)"
                          style="display: none;">
                        <button class="select-file-btn" @click="$refs.caseApprovalInput.click()">
                          选择文件
                        </button>
                        <span v-if="penaltyFiles.caseApproval" class="file-name">
                          {{ penaltyFiles.caseApproval.name }}
                        </span>
                      </div>
                    </div>

                    <!-- 询问笔录上传 -->
                    <div class="file-upload-item">
                      <div class="file-upload-header">
                        <label>询问笔录（可选）</label>
                        <span v-if="penaltyFiles.interrogation" class="file-status success">✓ 已选择</span>
                        <span v-else class="file-status">○ 未选择</span>
                      </div>
                      <div class="file-upload-control">
                        <input
                          type="file"
                          ref="interrogationInput"
                          accept=".docx,.doc"
                          @change="handlePenaltyFileSelect('interrogation', $event)"
                          style="display: none;">
                        <button class="select-file-btn" @click="$refs.interrogationInput.click()">
                          选择文件
                        </button>
                        <span v-if="penaltyFiles.interrogation" class="file-name">
                          {{ penaltyFiles.interrogation.name }}
                        </span>
                      </div>
                    </div>

                    <!-- 证据文件上传 -->
                    <div class="file-upload-item">
                      <div class="file-upload-header">
                        <label>证据文件（可选，可多选）</label>
                        <span v-if="penaltyFiles.evidence.length > 0" class="file-status success">
                          ✓ 已选择{{ penaltyFiles.evidence.length }}个文件
                        </span>
                        <span v-else class="file-status">○ 未选择</span>
                      </div>
                      <div class="file-upload-control">
                        <input
                          type="file"
                          ref="evidenceInput"
                          multiple
                          accept=".docx,.doc,.pdf,.jpg,.jpeg,.png"
                          @change="handlePenaltyFileSelect('evidence', $event)"
                          style="display: none;">
                        <button class="select-file-btn" @click="$refs.evidenceInput.click()">
                          选择文件
                        </button>
                        <div v-if="penaltyFiles.evidence.length > 0" class="evidence-file-list">
                          <div v-for="(file, index) in penaltyFiles.evidence" :key="index" class="evidence-file-item">
                            <span class="file-name">{{ file.name }}</span>
                            <button class="remove-file-btn" @click="removePenaltyEvidenceFile(index)">×</button>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 生成按钮 -->
                    <div class="generate-btn-container">
                      <button
                        class="generate-penalty-btn"
                        :class="{ disabled: !canGeneratePenalty }"
                        :disabled="!canGeneratePenalty"
                        @click="generatePenaltyDecisionDoc">
                        <span v-if="isGenerating">🔄 正在生成...</span>
                        <span v-else>📝 生成行政处罚决定书</span>
                      </button>
                    </div>

                    <!-- 提示信息 -->
                    <div class="upload-tips">
                      <p>💡 提示：必须上传立案审批表文件才能生成处罚决定书。系统将自动调用裁量标准智能体获取法律依据和罚款金额建议。</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 集体议案页面 -->
        <div v-else-if="selectedStage === 'collective_proposal'" class="document-preview">
          <div class="preview-container">
            <div class="preview-header">
              <h3>集体议案</h3>
              <div class="preview-actions">
                <span class="document-type">DOCX</span>
                <button v-if="proposalGenerated"
                        class="download-word-btn"
                        @click="downloadCollectiveProposal">
                  📥 下载Word文档
                </button>
              </div>
            </div>
            
            <div class="preview-content">
              <div class="document-generator">
                  <div class="document-header">
                    <h4>集体议案生成</h4>
                    <p>请输入相关处罚结果信息，系统将根据您的输入生成集体议案文档。</p>
                  </div>
                  
                  <div class="form-group">
                    <label for="proposalContent">处罚结果</label>
                    <textarea
                      id="proposalContent"
                      v-model="proposalContent"
                      class="text-input"
                      rows="12"
                      placeholder="请输入拟定的处罚结果">
                    </textarea>
                    <small class="form-hint">请确保处罚结果内容准确、完整，以便生成正式的集体议案文档。</small>
                  </div>
                  
                  <div v-if="proposalError" class="error-message">
                    {{ proposalError }}
                  </div>
                  
                  <div class="document-info">
                    <div class="info-card">
                      <div class="info-icon">ℹ️</div>
                      <div class="info-content">
                        <h5>注意事项</h5>
                        <ul>
                          <li>生成的集体议案将包含您输入的处罚结果</li>
                          <li>文档生成后可下载Word格式进行后续编辑</li>
                          <li>请确保输入内容符合消防行政执法规范</li>
                        </ul>
                      </div>
                    </div>
                  </div>
                  
                  <div class="generate-btn-container">
                    <button
                      class="generate-btn"
                      :disabled="isGeneratingProposal || !proposalContent.trim()"
                      @click="generateCollectiveProposal">
                      <span v-if="isGeneratingProposal">🔄 正在生成...</span>
                      <span v-else>📝 生成集体议案</span>
                    </button>
                  </div>
                  
                  <div v-if="proposalGenerated" class="success-message">
                    <p>✅ 集体议案生成成功！您可以下载Word文档进行查看和编辑。</p>
                    <p class="success-hint">请在下载后检查文档内容，确保所有信息准确无误。</p>
                  </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他文档预览 -->
        <div v-else-if="previewDocument" class="document-preview">
          <div class="preview-container">
            <div class="preview-header">
              <h3>{{ previewDocument.name }}</h3>
              <div class="preview-actions">
                <span class="document-type">{{ previewDocument.type.toUpperCase() }}</span>
                <button v-if="previewDocument.type === 'docx'"
                        class="download-word-btn"
                        @click="downloadFile(previewDocument.filePath)">
                  📥 下载Word文档
                </button>
              </div>
            </div>
            
            <div class="preview-content">
              <div v-if="previewDocument.type === 'pdf'" class="pdf-preview">
                <div class="pdf-frame-container">
                  <iframe 
                    v-if="previewDocument.filePath" 
                    :src="previewDocument.filePath" 
                    class="pdf-frame"
                    title="PDF预览">
                  </iframe>
                  <div v-else class="pdf-fallback">
                    <p>无法预览此文件</p>
                    <button class="preview-btn" @click="downloadFile(previewDocument.filePath)">下载文件</button>
                  </div>
                </div>
              </div>
              
              <div v-else-if="previewDocument.type === 'docx'" class="docx-preview">
                <!-- 使用docx-preview组件预览 -->
                <div class="docx-frame-container">
                  <div ref="generalPreviewContainer" class="docx-preview-wrapper" v-show="!isLoadingDocx"></div>
                  <!-- 加载中 -->
                  <div v-if="isLoadingDocx" class="html-loading">
                    <div class="loading-spinner"></div>
                    <p>正在加载文档预览...</p>
                  </div>
                </div>
              </div>
              
              <div v-else class="no-document-selected">
                <p>不支持的文件类型</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 默认显示 -->
        <div v-else class="document-preview">
          <div class="preview-container">
            <div class="preview-content">
              <div class="no-document-selected">
                <p>请从左侧菜单选择一个文档</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部对话框 -->
    <div class="chat-container" :class="{ 'chat-expanded': isChatExpanded }" :style="{ height: isChatExpanded ? chatHeight + 'px' : '40px' }">
      <!-- 拖动条 -->
      <div class="chat-resize-handle" v-if="isChatExpanded" @mousedown="startDrag"></div>
      
      <!-- 聊天头部 -->
      <div class="chat-header" @click="toggleChat">
        <div class="chat-title">
          <i class="chat-icon">🤖</i>
          <h4>AI智能问答</h4>
        </div>
        <div class="chat-actions">
          <span class="toggle-icon">{{ isChatExpanded ? '▼' : '▲' }}</span>
          <button v-if="isChatExpanded" class="action-icon" @click.stop>📋</button>
          <button v-if="isChatExpanded" class="action-icon" @click.stop>⚙️</button>
        </div>
      </div>
      
      <!-- 聊天内容区域 -->
      <div v-show="isChatExpanded" class="chat-content">
        <div class="chat-messages">
          <div v-for="(msg, index) in chatMessages" :key="index" 
            class="chat-message" 
            :class="{ 'user-message': msg.sender === 'user', 'system-message': msg.sender === 'system' }">
            <div class="message-avatar">
              {{ msg.sender === 'user' ? '👤' : '🤖' }}
            </div>
            <div class="message-bubble">
              <div class="message-content">{{ msg.content }}</div>
              <div class="message-time">{{ new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="chat-input-area">
          <input 
            type="text" 
            v-model="chatInput" 
            placeholder="输入您的问题或指令..." 
            class="chat-input"
            @keyup.enter="sendMessage">
          <button @click="sendMessage" class="send-btn">
            <span class="send-icon">📤</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 生成材料加载弹窗 -->
    <div v-if="isGenerating" class="loading-overlay">
      <div class="loading-modal">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <h3>正在生成材料</h3>
          <p>AI正在分析文档内容，请稍候...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局强制全屏样式 */
html, body {
  height: 100vh !important;
  width: 100vw !important;
  margin: 0 !important;
  padding: 0 !important;
  overflow: hidden !important;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh !important;
  width: 100vw !important;
  min-height: 100vh !important;
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  overflow: hidden;
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 响应式布局适配 */
@media (max-width: 1200px) {
  .left-panel {
    width: 200px;
  }
}

@media (max-width: 992px) {
  .header-left {
    gap: 15px;
  }
  
  .header-title {
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .left-panel {
    width: 180px;
  }
  
  .header {
    padding: 0 10px;
  }
  
  .header-btn {
    padding: 5px 10px;
    font-size: 12px;
  }
}

/* 顶部导航 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e1e8ed;
}

.header-left {
  display: flex;
  gap: 20px;
}

.header-title {
  padding: 5px 10px;
  cursor: pointer;
  color: #666;
}

.header-title.active {
  color: #1890ff;
  font-weight: bold;
  border-bottom: 2px solid #1890ff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-btn {
  padding: 5px 15px;
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.header-user {
  color: #666;
}

/* 主体内容 */
.main-content {
  display: flex;
  flex: 1 !important;
  height: 100% !important;
  width: 100% !important;
  overflow: hidden;
  position: relative;
}

/* 左侧阶段菜单 */
.left-panel {
  width: 220px !important;
  min-width: 220px !important;
  max-width: 220px !important;
  height: 100% !important;
  background-color: #fff;
  border-right: 1px solid #e1e8ed;
  overflow-y: auto;
  flex-shrink: 0 !important;
}

.stage-menu {
  padding: 10px 0;
}

.stage-item {
  margin-bottom: 5px;
}

.stage-header {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  cursor: pointer;
  font-weight: bold;
  color: #333;
}

.stage-header:hover {
  background-color: #f5f5f5;
}

.stage-arrow {
  margin-right: 10px;
  font-size: 12px;
}

.stage-submenu {
  background-color: #fafafa;
}

.stage-subitem {
  padding: 8px 40px;
  cursor: pointer;
  color: #666;
}

.stage-subitem:hover {
  background-color: #f0f0f0;
}

.stage-subitem.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-right: 3px solid #1890ff;
}

/* 右侧文档区域 */
.right-panel {
  flex: 1 !important;
  height: 100% !important;
  width: 100% !important;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 文档预览区域 */
.document-preview {
  flex: 1 !important;
  height: 100% !important;
  width: 100% !important;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  margin: 15px;
  border-radius: 4px;
  overflow: hidden;
  box-sizing: border-box !important;
}

.preview-container {
  display: flex;
  flex-direction: column;
  height: 100% !important;
  width: 100% !important;
  flex: 1 !important;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e1e8ed;
  background-color: #fafafa;
  flex-shrink: 0 !important;
}

.preview-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.preview-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.document-type {
  padding: 5px 10px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

.download-word-btn {
  padding: 8px 16px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s ease;
}

.download-word-btn:hover {
  background-color: #73d13d;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.preview-content {
  flex: 1 !important;
  height: 100% !important;
  width: 100% !important;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box !important;
}

.pdf-preview, .docx-preview {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1 !important;
}

.pdf-frame-container {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1 !important;
}

.pdf-frame {
  width: 100% !important;
  height: 100% !important;
  border: 1px solid #e1e8ed;
  border-radius: 4px;
  flex: 1 !important;
}

/* Word文档iframe样式，与PDF一致 */
.docx-frame-container {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1 !important;
}

/* docx-preview wrapper 样式 */
.docx-preview-wrapper {
  width: 100% !important;
  height: 100% !important;
  overflow-y: auto;
  border: 1px solid #e1e8ed;
  border-radius: 4px;
  background-color: #fff;
}

.docx-frame {
  width: 100% !important;
  height: 100% !important;
  border: 1px solid #e1e8ed;
  border-radius: 4px;
  flex: 1 !important;
}

.docx-fallback {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
  background-color: #f9f9f9;
  border-radius: 4px;
  height: 100%;
  width: 100%;
}

/* Word文档预览信息样式 */
.word-preview-info {
  max-width: 400px;
  margin: 0 auto;
}

.word-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.word-preview-info h4 {
  color: #333;
  margin: 0 0 10px 0;
  font-size: 18px;
}

.file-name {
  color: #666;
  margin: 0 0 25px 0;
  font-size: 14px;
  font-weight: 500;
}

.preview-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 20px;
}

.preview-btn.primary {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.preview-btn.primary:hover {
  background-color: #40a9ff;
  transform: translateY(-1px);
}

.preview-btn.secondary {
  background-color: #fff;
  color: #666;
  border: 1px solid #d9d9d9;
  padding: 12px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.preview-btn.secondary:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.btn-icon {
  font-size: 16px;
}

.preview-tip {
  color: #999;
  margin: 0;
  line-height: 1.4;
}

.pdf-fallback {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
  background-color: #f9f9f9;
  border-radius: 4px;
  height: 100%;
  width: 100%;
}

.preview-btn {
  margin-top: 15px;
  margin-right: 10px;
  padding: 8px 20px;
  background-color: #52c41a;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.preview-btn:hover {
  background-color: #73d13d;
}

/* PDF全屏查看样式 */
.pdf-fullscreen-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
}

.pdf-fullscreen-viewer {
  width: 95%;
  height: 95%;
  border: none;
  background-color: white; /* 确保PDF背景是白色的 */
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.5);
}

.pdf-fullscreen-close {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  color: #333;
  font-size: 24px;
  border: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  z-index: 10000; /* 确保按钮在最上层 */
  transition: all 0.2s ease;
}

.pdf-fullscreen-close:hover {
  background-color: #f0f0f0;
  transform: scale(1.1);
}

/* PDF工具栏 */
.pdf-toolbar {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
}

.toolbar-btn {
  padding: 5px 10px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.toolbar-btn:hover {
  background-color: #40a9ff;
}

.docx-frame {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.docx-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.docx-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.upload-area {
  width: 100%;
  min-height: 200px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f7ff;
}

.upload-content {
  text-align: center;
  margin-bottom: 20px;
}

.upload-content p {
  color: #333;
  margin-bottom: 8px;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
  color: #1890ff;
}

.upload-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-btn:hover {
  background-color: #40a9ff;
}

.upload-progress {
  width: 80%;
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  margin-top: 10px;
}

.progress-bar {
  height: 100%;
  background-color: #52c41a;
  transition: width 0.3s;
}

.upload-success {
  color: #52c41a;
  font-weight: bold;
  margin-top: 10px;
}

.preview-placeholder,
.no-document-selected {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #999;
}

.preview-placeholder p,
.no-document-selected p {
  margin: 5px 0;
}

.download-btn {
  margin: 0;
  padding: 6px 16px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.upload-error {
  color: #ff4d4f;
  font-weight: bold;
  margin-top: 10px;
}

.download-btn:hover {
  background-color: #40a9ff;
}

/* HTML内容显示样式 - 保持与其他预览一致的布局 */
.html-content-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background-color: #fff;
}

.html-content {
  width: 100%;
  height: auto;
  min-height: 100%;
  box-sizing: border-box;
}

/* HTML内容中的表格样式 */
.html-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
  font-size: 14px;
}

.html-content table th,
.html-content table td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: left;
  vertical-align: top;
}

.html-content table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

/* HTML内容中的标题样式 */
.html-content h1, .html-content h2, .html-content h3 {
  color: #333;
  margin: 20px 0 10px 0;
  text-align: center;
}

.html-content h1 {
  font-size: 18px;
  font-weight: bold;
}

.html-content h2 {
  font-size: 16px;
  font-weight: bold;
}

.html-content h3 {
  font-size: 14px;
  font-weight: bold;
}

/* HTML内容中的段落样式 */
.html-content p {
  margin: 10px 0;
  text-indent: 0;
}

/* HTML加载状态样式 */
.html-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #666;
}

.html-loading .loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}
.generate-btn-container {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

/* 生成材料按钮 */
.generate-btn {
  padding: 12px 48px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: background-color 0.3s;
  min-width: 200px;
}

.generate-btn:hover:not(.disabled) {
  background-color: #73d13d;
}

.generate-btn.disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 文档上传容器 */
.documents-upload-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  padding: 20px;
  flex: 1 !important; /* 替换max-height限制 */
  height: 100% !important;
  width: 100% !important;
  align-self: stretch !important; /* 替换center对齐 */
  box-sizing: border-box;
  justify-content: center;
  align-content: start;
}

/* 确保文件上传区域在小屏幕上正确显示 */
@media (max-width: 768px) {
  .documents-upload-container {
    grid-template-columns: 1fr;
  }
}

.document-upload-item {
  background-color: #fafafa;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #e8e8e8;
}

.document-upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.document-upload-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

/* 上传状态徽章 */
.upload-status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.upload-status-badge.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.upload-status-badge.uploading {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.upload-status-badge.error {
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.upload-status-badge {
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #d9d9d9;
}

/* 提示信息 */
.upload-tips {
  padding: 15px 20px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-top: 1px solid #bae7ff;
  font-size: 14px;
  margin-top: auto;
  width: 100%;
  box-sizing: border-box;
}

.upload-tips p {
  margin: 0;
}

/* 小尺寸下载按钮 */
.download-btn.small {
  margin-left: 10px;
  padding: 4px 12px;
  font-size: 12px;
  background-color: #1890ff;
}

.download-btn.small:hover {
  background-color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .documents-upload-container {
    grid-template-columns: 1fr;
  }
}

.search-bar {
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #e1e8ed;
}

.search-input {
  width: 100%;
  padding: 8px 15px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.case-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 15px;
}

.case-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.tab {
  padding: 8px 20px;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  color: #666;
}

.tab.active {
  background-color: #1890ff;
  color: #fff;
  border-color: #1890ff;
}

.case-grid {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.case-item {
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.case-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.case-item.active {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.case-number {
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 10px;
}

.case-name {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.case-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.case-description {
  font-size: 12px;
  color: #888;
  margin-top: 10px;
  line-height: 1.5;
}

/* 案件详情 */
.case-detail {
  background-color: #fff;
  border-top: 1px solid #e1e8ed;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-header h3 {
  margin: 0;
  color: #333;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 5px 15px;
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.detail-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.form-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.form-item {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 200px;
}

.form-item.full-width {
  min-width: 100%;
}

.form-item label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.form-item span {
  font-size: 14px;
  color: #333;
}

.case-highlight {
  color: #1890ff;
  font-weight: bold;
}

/* 底部对话框 */
.chat-container {
  position: relative;
  background-color: #f9fafc;
  border-top: 1px solid #e1e8ed;
  display: flex;
  flex-direction: column;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  transition: height 0.3s ease;
  overflow: hidden;
}

.chat-expanded {
  border-top: 1px solid #1890ff;
}

.chat-resize-handle {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 5px;
  cursor: ns-resize;
  background-color: transparent;
  z-index: 100;
}

.chat-resize-handle:hover {
  background-color: rgba(24, 144, 255, 0.1);
}

.chat-header {
  padding: 8px 15px;
  border-bottom: 1px solid #eaedf1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-header:hover {
  background-color: #f0f7ff;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-icon {
  font-size: 16px;
  color: #1890ff;
  font-style: normal;
}

.chat-header h4 {
  margin: 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.chat-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.toggle-icon {
  font-size: 12px;
  color: #666;
  transition: transform 0.3s;
}

.chat-expanded .toggle-icon {
  transform: rotate(180deg);
}

.action-icon {
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  padding: 2px;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.action-icon:hover {
  opacity: 1;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f9fafc;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 10px 15px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chat-message {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  max-width: 85%;
}

.message-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  flex-shrink: 0;
}

.message-bubble {
  padding: 8px 12px;
  border-radius: 12px;
  position: relative;
}

.message-content {
  color: #333;
  line-height: 1.5;
  font-size: 13px;
  word-break: break-word;
}

.message-time {
  font-size: 10px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.user-message .message-bubble {
  background-color: #e6f7ff;
  border: 1px solid #bae7ff;
  border-bottom-right-radius: 2px;
}

.system-message .message-bubble {
  background-color: #fff;
  border: 1px solid #eaedf1;
  border-bottom-left-radius: 2px;
}

.chat-input-area {
  display: flex;
  gap: 10px;
  padding: 10px 15px;
  border-top: 1px solid #eaedf1;
  background-color: #fff;
}

.chat-input {
  flex: 1;
  padding: 8px 15px;
  border: 1px solid #d9d9d9;
  border-radius: 18px;
  font-size: 13px;
  transition: border-color 0.3s;
  background-color: #f5f7fa;
}

.chat-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  background-color: #fff;
}

.send-btn {
  width: 36px;
  height: 36px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s;
}

.send-btn:hover {
  background-color: #40a9ff;
}

.send-icon {
  font-size: 14px;
}

/* 加载弹窗样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

.loading-modal {
  background-color: #fff;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  max-width: 360px;
  width: 90%;
  animation: modalFadeIn 0.3s ease-out;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.loading-content h3 {
  margin: 20px 0 10px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.loading-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 询问笔录生成页面样式 */
.interrogation-generation-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

/* 行政处罚告知笔录生成页面样式 - 重用询问笔录样式 */
.notice-generation-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  overflow-y: auto;
}

.notice-generation-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  max-width: 800px;
  width: 100%;
}

.interrogation-generation-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  overflow-y: auto;
}

/* 告知类型选择样式 */
.gaozhi-type-selection {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.gaozhi-type-selection h5 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.radio-group {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 10px 15px;
  background-color: #fff;
  border-radius: 6px;
  border: 2px solid #d9d9d9;
  transition: all 0.2s ease;
}

.radio-label:hover {
  border-color: #1890ff;
}

.radio-label:has(.radio-input:checked) {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.radio-input {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.radio-text {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.generate-notice-btn {
  padding: 12px 32px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s ease;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.generate-notice-btn:hover:not(:disabled) {
  background-color: #40a9ff;
  transform: translateY(-1px);
}

.generate-notice-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
  transform: none;
}

/* 询问笔录生成页面样式 */
.interrogation-generation-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
}

.generation-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e8e8e8;
}

.info-header h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.info-content p {
  margin: 0 0 10px 0;
  color: #555;
  line-height: 1.6;
}

.info-content ul {
  margin: 10px 0 0 20px;
  color: #555;
}

.info-content li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.generation-status {
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  border: 1px solid #e8e8e8;
  text-align: center;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.status-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.generation-status h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.generation-status p {
  margin: 0 0 15px 0;
  color: #666;
  line-height: 1.6;
  max-width: 400px;
}

.status-tip {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 10px 15px;
  border-radius: 6px;
  margin-top: 10px !important;
  border: 1px solid #bae7ff;
}

.generate-interrogation-btn {
  padding: 12px 32px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s ease;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.generate-interrogation-btn:hover:not(:disabled) {
  background-color: #40a9ff;
  transform: translateY(-1px);
}

.generate-interrogation-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
  transform: none;
}

.completed-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
  justify-content: center;
}

.action-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.action-btn.preview-btn {
  background-color: #52c41a;
  color: white;
}

.action-btn.preview-btn:hover {
  background-color: #73d13d;
  transform: translateY(-1px);
}

.action-btn.download-btn {
  background-color: #1890ff;
  color: white;
}

.action-btn.download-btn:hover {
  background-color: #40a9ff;
  transform: translateY(-1px);
}

/* ==================== 行政处罚决定书样式 ==================== */

/* 处罚决定书生成容器 */
.penalty-generation-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  overflow-y: auto;
}

.penalty-generation-container {
  max-width: 900px;
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 文件上传区域 */
.file-upload-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e8e8e8;
}

.file-upload-section h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.file-upload-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.file-upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.file-upload-header label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.file-status {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #d9d9d9;
}

.file-status.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.file-upload-control {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.select-file-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
  width: fit-content;
}

.select-file-btn:hover {
  background-color: #40a9ff;
}

.file-upload-control .file-name {
  font-size: 13px;
  color: #666;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

/* 证据文件列表 */
.evidence-file-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 10px;
}

.evidence-file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.evidence-file-item .file-name {
  font-size: 13px;
  color: #666;
  flex: 1;
  padding: 0;
  background: none;
  border: none;
}

.remove-file-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.2s;
  margin-left: 10px;
}

.remove-file-btn:hover {
  background-color: #ff7875;
}

/* 生成按钮 */
.generate-btn, .generate-penalty-btn {
  padding: 12px 32px;
  background-color: #52c41a;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 auto;
}

.generate-btn:hover:not(:disabled), .generate-penalty-btn:hover:not(.disabled) {
  background-color: #73d13d;
  transform: translateY(-1px);
}

.generate-btn:disabled, .generate-penalty-btn.disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
  transform: none;
}

/* 集体议案样式 */
.proposal-content {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
}

/* 表单样式 */
.document-generator {
  padding: 25px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.document-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.document-header h4 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 18px;
  font-weight: 600;
}

.document-header p {
  margin: 0;
  color: #595959;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-hint {
  display: block;
  margin-top: 5px;
  color: #8c8c8c;
  font-size: 12px;
  line-height: 1.4;
}

.text-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
  line-height: 1.5;
  resize: vertical;
  min-height: 120px;
  transition: border-color 0.3s;
}

.text-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.text-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.error-message {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 15px;
  color: #ff4d4f;
  font-size: 14px;
}

.document-info {
  margin: 25px 0;
}

.info-card {
  display: flex;
  gap: 15px;
  padding: 15px;
  background-color: #f0f5ff;
  border: 1px solid #adc6ff;
  border-radius: 4px;
}

.info-icon {
  font-size: 24px;
  flex-shrink: 0;
  margin-top: 2px;
}

.info-content h5 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.info-content ul {
  margin: 0;
  padding-left: 20px;
}

.info-content li {
  margin-bottom: 4px;
  color: #595959;
  font-size: 13px;
  line-height: 1.5;
}

.info-content li:last-child {
  margin-bottom: 0;
}

.success-message {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
  padding: 15px;
  margin-top: 20px;
  color: #52c41a;
  font-size: 14px;
}

.success-hint {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e6f7ff;
  color: #8c8c8c;
  font-size: 13px;
}

.generate-btn-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 15px;
}

/* ==================== 行政处罚决定书样式结束 ==================== */

</style>